const childProcess = require('child_process');

export const commands = {
  execCommandSync(cmd: string, ...args: string[]): string {
    const buffer = childProcess.execSync([cmd, ...args].join(' '));
    return buffer.toString('ascii');
  },

  /**
   * @param opts
   * @param opts.cmd
   * @param opts.timeout 执行命令超时时间
   * @param opts.reject 等于false时,执行命令出错不抛出异常
   * @param args
   */
  execCommand(opts: { cmd: string; timeout?: number; reject?: boolean } | string, ...args: string[]): Promise<string> {
    return new Promise((resolve, reject) => {
      const cmd = typeof opts === 'string' ? opts : opts.cmd;
      const rejectable = typeof opts === 'string' || opts.reject !== false;

      childProcess.exec([cmd, ...args].join(' '), (error: any, stdout: string) => {
        if (error) {
          rejectable ? reject(error) : resolve('');
          return;
        }
        resolve(stdout);
      });

      if (typeof opts === 'object' && opts.timeout && opts.timeout > 0) {
        setTimeout(() => {
          rejectable ? reject({ cmd, message: `Command timeout` }) : resolve('');
        }, opts.timeout);
      }
    });
  }
};
